/*
 * Copyright 2006 Google Inc.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
package com.google.gwt.user.client.ui;

import java.util.Iterator;

/**
 * Abstract base class for all panels, which are widgets that can contain other
 * widgets.
 */
public abstract class Panel extends Widget implements HasWidgets {

  /**
   * Adds a new child widget to the panel.
   * 
   * @param w the child widget to be added
   * @return <code>true</code> on success (some panels place restrictions on
   *         how children may be added or inserted)
   */
  public abstract boolean add(Widget w);

  /**
   * Removes all widgets from this panel.
   */
  public abstract void clear();

  /**
   * This method must be called whenever a Widget is removed. It ensures that
   * the Widget's parent is cleared.
   */
  protected void disown(Widget w) {
    w.setParent(null);
  }

  /**
   * This method must be called as part of the add method of any panel. It
   * ensures that the Widget's parent is set properly.
   */
  protected void adopt(Widget w) {
    w.setParent(this);
  }

  /**
   * Removes a widget from the panel.
   * 
   * @param w the widget to be removed
   * @return <code>true</code> if the widget was present
   */
  public abstract boolean remove(Widget w);

  protected final void onAttach() {
    super.onAttach();

    // Ensure that all child widgets are attached.
    for (Iterator it = iterator(); it.hasNext();) {
      Widget child = (Widget) it.next();
      child.onAttach();
    }
  }

  protected final void onDetach() {
    super.onDetach();

    // Ensure that all child widgets are detached.
    for (Iterator it = iterator(); it.hasNext();) {
      Widget child = (Widget) it.next();
      child.onDetach();
    }
  }
}
